/***************************************************
  > Copyright (C) 2024 ==KINGYI== All rights reserved.
  > File Name: 8.3.2.c
  > Author:
  > Mail: 
  > Created Time: Fri 02 Aug 2024 10:58:53 PM PDT
 ***************************************************/

//目录中有两个文件，创建一个子进程，父和子分别拷贝其中一个文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
int file_cpy(char *filename, char *copy_filename);

int main(int argc, const char* argv[])
{
	pid_t pid = 0;
	pid = fork();

	if(pid == 0)
	{
		file_cpy("./music/temp.txt","./music/test.txt");
		printf("子进程读取成功\n");
		exit(0);
	}else
	{
		file_cpy("./2024/1.txt","./2024/2.txt");
		printf("父进程读取成功\n");
	}
	wait(NULL);
	return 0;
}

int file_cpy(char *filename, char* cp_filename)
{

	int fd = 0,fu = 0;
	char dest[1024] = {0};
	int ret = 0,res = 0;
    //定义变量


	fd = open(filename,O_RDONLY); //打开文件1
	if(fd == -1)
	{
		perror("open");
		exit(-1);
	}

	fu = open(cp_filename,O_RDWR|O_CREAT|O_APPEND,0640); //打开文件2
	if(fu == -1)
	{
		perror("open");
		exit(-1);
	}
    ret = read(fd,dest,sizeof(dest));
	while(ret !=0)
	{
		res = write(fu,dest,ret);
		if(res == -1 )
		{
         perror("wtite");
		 exit(-1);

		}
		ret = read(fd,dest,sizeof(dest));
		if(ret == -1)
	{
	perror("read");
	}
	}
	
	close (fd);
	close(fu);
	return 0;
}
